<template>
  <div>
    <!--面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!--卡片区域-->
    <el-card class="box-card">
      <el-button type="primary" @click="showAddDialog()">添加分类</el-button>
      <table-tree
        :data="categoriesList"
        :columns="categoriesListColumns"
        :selection-type="false"
        :expand-type="false"
        show-index
      >
        <template slot="deleted" slot-scope="scope">
          <i
            class="el-icon-circle-check"
            style="color:rgb(68, 178, 170)"
            v-if="scope.row.cat_deleted===false"
          ></i>
          <i class="el-icon-circle-close" style="color:red;" v-else></i>
        </template>
        <template slot="order" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level===0">一级</el-tag>
          <el-tag type="success" v-else-if="scope.row.cat_level===1">二级</el-tag>
          <el-tag type="warning" v-else>三级</el-tag>
        </template>
        <template slot="opt" slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="showEditDialog(scope.row.cat_id)"
          >编辑</el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="delCate(scope.row.cat_id)"
          >删除</el-button>
        </template>
      </table-tree>

      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-size="queryInfo.pagesize"
        layout="total,  prev, pager, next, jumper"
        :total="total"
      ></el-pagination>

      <!--添加分类弹层-->
      <el-dialog title="添加分类" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
          <el-form-item label="活动名称" prop="cat_name">
            <el-input v-model="addForm.cat_name"></el-input>
          </el-form-item>

          <el-form-item label="分类上级">
            <el-cascader
              expand-trigger="hover"
              :options="cateTwoList"
              :props="cateTwoListProps"
              v-model="selectedCateTwo"
              @change="cateTwoChange"
              change-on-select
              clearable
              style="width:100%"
            ></el-cascader>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addCate">确 定</el-button>
        </span>
      </el-dialog>

      <!--修改分类弹层-->
      <el-dialog
        title="修改分类"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editDialogClosed"
      >
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
          <el-form-item label="活动名称" prop="cat_name">
            <el-input v-model="editForm.cat_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editCate">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 分类数据列表
      categoriesList: [],
      // 获取信息的请求参数
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      // 记录总条数
      total: 0,
      /** table-tree 表格相关1 */
      categoriesListColumns: [
        { label: '分类名称', prop: 'cat_name', width: '200px' },
        {
          label: '是否有效',
          prop: 'cat_deleted',
          width: '200px',
          type: 'template',
          template: 'deleted'
        },
        {
          label: '排序',
          prop: 'cat_level',
          width: '200px',
          type: 'template',
          template: 'order'
        },
        {
          label: '操作',
          prop: 'cat_deleted',
          width: '200px',
          type: 'template',
          template: 'opt'
        }
      ],
      /** table-tree 表格相关2 */

      /** 添加分类1 */
      addDialogVisible: false,
      // 表单数据
      addForm: {
        cat_pid: 0,
        cat_name: '',
        cat_level: 0
      },
      // 校验规则
      addFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      // 供选取的分类数据
      cateTwoList: [],
      // 供选取分类数据对应的"名称和有效值"对象
      cateTwoListProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 被选中分类的接收对象
      selectedCateTwo: [],
      /** 添加分类2 */

      /** 修改分类1 */
      editDialogVisible: false,
      // 表单数据
      editForm: {
        cat_name: ''
      },
      // 校验规则
      editFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      }
      /** 修改分类2 */
    }
  },
  created() {
    this.getCategoriesList()
  },
  methods: {
    /** 删除分类1 */
    async delCate(catId) {
      const cfm = await this.$confirm('确认要删除该分类么?', '删除分类', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (cfm === 'confirm') {
        const { data: res } = await this.$http.delete('categories/' + catId)
        if (res.meta.status !== 200) {
          return this.$message({
            message: '删除分类失败',
            type: 'error',
            duration: 1000
          })
        }

        // 页面刷新
        this.getCategoriesList()
        // 提示
        this.$message({
          message: '删除分类成功',
          type: 'success',
          duration: 1000
        })
      }
    },
    /** 删除分类2 */

    /** 修改分类1 */
    // 展示修改分类的弹层
    async showEditDialog(catId) {
      // 获得cat_id对应的分类信息
      const { data: res } = await this.$http.get('categories/' + catId)
      if (res.meta.status !== 200) {
        return this.$message({
          message: '获取被修改分类失败',
          type: 'error',
          duration: 1000
        })
      }

      // 把被修改分类信息赋予给editForm表单对象
      this.editForm = res.data
      this.editDialogVisible = true
    },

    // 校验 并 存储 数据到服务器
    editCate() {
      this.$refs.editFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.put(
            'categories/' + this.editForm.cat_id,
            this.editForm
          )

          if (res.meta.status !== 200) {
            return this.$message({
              message: '修改分类失败',
              type: 'error',
              duration: 1000
            })
          }

          // 关闭弹层
          this.editDialogVisible = false
          // 页面更新
          this.getCategoriesList()
          // 提示
          this.$message({
            message: '修改分类成功',
            type: 'success',
            duration: 1000
          })
        }
      })
    },

    // 弹层 关闭后的 回调
    editDialogClosed() {
      // 清除表单信息
      this.$refs.editFormRef.resetFields()
    },
    /** 修改分类2 */

    /** 添加分类1 */
    // 收集数据存储
    addCate() {
      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.post(
            'categories',
            this.addForm
          )
          if (res.meta.status !== 201) {
            return this.$message({
              message: '添加分类失败',
              type: 'error',
              duration: 1000
            })
          }

          // 关闭弹层
          this.addDialogVisible = false
          // 提示信息
          this.$message({
            message: '添加分类成功',
            type: 'success',
            duration: 1000
          })
          // 刷新数据
          this.getCategoriesList()
        }
      })
    },

    // 展示添加分类Dialog弹层
    async showAddDialog() {
      // 获取可供选取的二级分类信息
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 }
      })

      if (res.meta.status !== 200) {
        return this.$message({
          message: '获取上级分类信息失败',
          type: 'error',
          duration: 1000
        })
      }
      this.cateTwoList = res.data
      this.addDialogVisible = true
    },

    // 点击取消 按钮关闭弹层
    addDialogClosed() {
      // 清除表单信息
      this.$refs.addFormRef.resetFields()
      // 清除之前选中的信息
      this.selectedCateTwo = []
      // // 清除之前记录的选中信息
      this.addForm.cat_pid = 0
      this.addForm.cat_level = 0
    },

    // 鼠标切换选中分类项目事件触发
    cateTwoChange() {
      // 选取父级 需要记录给addForm.cat_pid表单域
      if (this.selectedCateTwo.length === 0) {
        // 上级id
        this.addForm.cat_pid = 0
        // 分类等级
        this.addForm.cat_level = 0
      } else {
        var len = this.selectedCateTwo.length
        this.addForm.cat_pid = this.selectedCateTwo[len - 1]
        this.addForm.cat_level = len
      }
    },
    /** 添加分类2 */

    // 页码切换处理
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getCategoriesList()
    },
    // 获取全部分类信息
    async getCategoriesList() {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message({
          message: '获取分类信息失败！',
          type: 'error',
          duration: 1000
        })
      }
      this.categoriesList = res.data.result
      this.total = res.data.total
    }
  }
}
</script>

<style lang="less" scoped>
// 给table-tree设置外边距
.zk-table {
  margin-top: 15px;
}
</style>
